package com.zt.bus.assistant.service;

import com.zt.bus.assistant.inter.RouteStatMapper;
import com.zt.bus.assistant.model.RouteStat;
import com.zt.bus.constant.BusConstant;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class RouteStatService extends BaseService {

    @Autowired
    private RouteStatMapper routeStatMapper;
    @Autowired
    private CacheManager cacheManager;

    Cache stopCache;

    /**
     * 查询
     *
     * @param reqBean
     * @return
     */
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select * from DZ_ROUTE_STAT where 1=1 ");

        sqlBuilder.addWhereLike2("START_STOP_NAME", reqBean.getInfo("startStopName"));
        sqlBuilder.addWhereLike2("END_STOP_NAME", reqBean.getInfo("endStopName"));
        sqlBuilder.addWhere("IS_WORKING_DEPART", reqBean.getInfo("isWorkingDepart"));
        sqlBuilder.addWhere("IS_HOLIDAY_DEPART", reqBean.getInfo("isHolidayDepart"));

        sqlBuilder.addTimeWhere("DEPART_TIME", reqBean.getInfo("departTimeStart"), ">=");
        sqlBuilder.addTimeWhere("DEPART_TIME", reqBean.getInfo("departTimeEnd"), "<=");

        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 查询所有站点
     *
     * @return
     */
    @Cacheable(value = BusConstant.Cache.STOP)
    public JSONArray getStops() {
        return this.query("select * from DZ_BUS_STOP where LNG is not null and LNG != '0'");
    }

    /**
     * 查询距离中心最近的站点（移动端）
     *
     * @return
     */
    @Cacheable(value = BusConstant.Cache.STOP)
    public JSONArray getStopsNearBy(ReqBean reqBean) {

        double lng = reqBean.getInfoDouble("lng");
        double lat = reqBean.getInfoDouble("lat");

//        JSONObject joCenter = JSONObject.fromObject(reqBean.getInfo("center"));
        double radius = reqBean.getInfoDouble("radius");
        int num = reqBean.getInfoInt("num");

        double radius_d = radius * 0.00001;

        double minLng = lng - radius_d;
        double minLat = lat - radius_d;

        double maxLng = lng + radius_d;
        double maxLat = lat + radius_d;

        String sql = "select * from DZ_BUS_STOP where LNG between ? and ? and LAT between ? and ? limit ?";
        JSONArray jaStops = this.query(sql, new Object[]{minLng, maxLng, minLat, maxLat, num});

        return jaStops;
    }

    /**
     * 根据线路查询
     *
     * @param reqBean
     * @return
     */
    public JSONArray getByRoute(ReqBean reqBean) {

        SqlBuilder sqlBuilder = new SqlBuilder("");

        String sql = "select t.DEPART_TIME, t.IS_WORKING_DEPART, t.IS_HOLIDAY_DEPART, t.START_STOP_NAME, t.START_STOP_LNG, t.START_STOP_LAT" +
                     ", t.END_STOP_NAME, t.END_STOP_LNG, t.END_STOP_LAT, count(t.ROUTE_ID) as NUM " +
                     "from DZ_ROUTE_STAT t where 1=1 "
                     //+ "and t.START_STOP_NAME = '中山大道大智路' "
                     ;

        sqlBuilder.appendSql(sql);
        sqlBuilder.addWhereLike2("START_STOP_NAME", reqBean.getInfo("startStopName"));
        sqlBuilder.addWhereLike2("END_STOP_NAME", reqBean.getInfo("endStopName"));
        sqlBuilder.addWhere("IS_WORKING_DEPART", reqBean.getInfo("isWorkingDepart"));
        sqlBuilder.addWhere("IS_HOLIDAY_DEPART", reqBean.getInfo("isHolidayDepart"));
        sqlBuilder.addTimeWhere("DEPART_TIME", reqBean.getInfo("departTimeStart"), ">=");
        sqlBuilder.addTimeWhere("DEPART_TIME", reqBean.getInfo("departTimeEnd"), "<=");
        sqlBuilder.appendSql("GROUP BY t.START_STOP_ID, t.END_STOP_ID");

        return this.query(sqlBuilder);
    }

    /**
    * 通过id查询
    *
    * @param routeId
    * @return
    */
    public RouteStat getById(String routeId) {
        return routeStatMapper.selectByPrimaryKey(routeId);
    }

    /**
    * 新增
    *
    * @param routeStat
    */
    public JSONObject add(RouteStat routeStat) {

        JSONObject joRet = new JSONObject();

        // routeStat.setUserId("1");

        switch (routeStat.getDepartType()){
            case "1":
                routeStat.setIsWorkingDepart("1");
                routeStat.setIsHolidayDepart("0");
                break;
            case "2":
                routeStat.setIsWorkingDepart("0");
                routeStat.setIsHolidayDepart("1");
                break;
            case "3":
                routeStat.setIsWorkingDepart("1");
                routeStat.setIsHolidayDepart("1");
                break;
        }

        String sql = "select count(*) as num from DZ_ROUTE_STAT t where t.USER_ID = ? and t.DEPART_TIME = ? and t.IS_WORKING_DEPART = ? and t.IS_HOLIDAY_DEPART = ? and t.START_STOP_ID = ? and t.END_STOP_ID = ?";
        JSONArray jaRoute = this.query(sql, new Object[]{routeStat.getUserId(),routeStat.getDepartTime(),routeStat.getIsWorkingDepart(),routeStat.getIsHolidayDepart(),routeStat.getStartStopId(),routeStat.getEndStopId()} );

        if( Integer.parseInt(jaRoute.getJSONObject(0).getString("num")) > 0 ){
            //throw new BusinessException("此方案已经登记！");
            joRet.put("resultCode", "0");
            joRet.put("resultMessage", "此方案已经登记！");
            return joRet;
        }
        routeStat.setRouteId(stringId());// 手动设置Id

        routeStat.setMakeTime(new Date());
        routeStat.setModifyTime(routeStat.getMakeTime());
        int ret = routeStatMapper.insert(routeStat);

        joRet.put("resultCode", "1");
        joRet.put("resultMessage", "登记成功！");
        return joRet;
    }

    /**
    * 修改
    *
    * @param routeStat
    */
    public void update(RouteStat routeStat) {
        String routeId = routeStat.getRouteId();
        if (StringUtil.isEmpty(routeId)) {
            throw new BusinessException("获取主键失败");
        }

        routeStat.setModifyTime(new Date());
        routeStatMapper.updateByPrimaryKeySelective(routeStat);
    }

    /**
    * 删除
    *
    * @param routeId
    */
    public void delete(String routeId) {
        if (StringUtil.isEmpty(routeId)) {
            throw new BusinessException("获取主键失败");
        }
        routeStatMapper.deleteByPrimaryKey(routeId);
    }

}